const router = require('koa-router')()
const Unit = require('../dbs/models/unit')

router.prefix('/units')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a units response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a units/bar response'
})

router.post('/addUnit', async function (ctx) {
  const unit = new Unit({
    name: ctx.request.body.name
  })
  let code
  let msg
  const result = await Unit.findOne({name: ctx.request.body.name})
  try {
    if(result){
      code = -1
      msg = '已存在'
    } else {
      await unit.save()
      code = 0
      msg = '添加成功'
    }
    
  } catch (e) {
    code = -1
  }
  ctx.body = {
    code: code,
    msg: msg
  }
})

router.post('/getUnit', async function(ctx) {
  const result = await Unit.findOne({name: ctx.request.body.name})
  const results = await Unit.find()
  ctx.body = {
    code: 0,
    result,
    results
  }
})

module.exports = router
